import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String [] args) throws EOFException{
        System.out.println("客户端启动...");
        Thread thread=new Thread(()->{
            try (
                    Socket socket=new Socket("127.0.0.1",8888);
                    DataInputStream inputStream=new DataInputStream(socket.getInputStream());
                    DataOutputStream outputStream=new DataOutputStream(socket.getOutputStream());
            ){
                // 打开指定的串口
                try {
                    CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM3");
                    try {
                        SerialPort sPort = (SerialPort) portId.open("COM3", 5000);

                        // 从串口中读取数据
                        while(true) {
                            InputStream isComm = new BufferedInputStream(sPort.getInputStream());
                            byte[] readBuffer = new byte[isComm.available()];

                            int len = 0;
                            String aString = null;

                            while((len = isComm.read(readBuffer)) != -1) {
                                aString = new String(readBuffer, 0, len).trim();

                                // 发送到服务器
                                if(aString.equals("bye"))break;
                                outputStream.writeUTF(aString);
                                System.out.println(aString + "已发送！");
                                outputStream.flush();

                                isComm.close();
                                isComm = null;
                                break;
                            }

                            try {
                                Thread.sleep(50);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                    }
                } catch (NoSuchPortException e) {
                    e.printStackTrace();
                }

                String iString=inputStream.readUTF();
                System.out.println(iString);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (ConnectException e) {
                System.out.println("服务器未启动！");
            }catch (IOException e) {//必须放在所有的catch的最后
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("客户端停止");
        });
        thread.start();
    }
}
